package ch.elca.lol.puissance4.player.ui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

import javax.swing.JFrame;

import ch.elca.lol.puissance4.board.Board;
import ch.elca.lol.puissance4.game.Token;
import ch.elca.lol.puissance4.player.PlayerHelper;

// TODO should be usable to watch AI matches
public class UIPlayer extends PlayerHelper {
	private final JFrame fr;
	private final BoardPanel bp;
	
	private final SynchronousQueue<Integer> play = new SynchronousQueue<Integer>();
	
	public UIPlayer() {
		bp = new BoardPanel();
		bp.addMouseListener(new ClicListener());
		
		fr = new JFrame("Connect-666");
		fr.add(bp);
		fr.validate();
		fr.pack();
		
		fr.setResizable(false);
		fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		fr.setVisible(true);
	}
	
	@Override
	public void setToken(Token t) {
		super.setToken(t);
		bp.setToken(t);
	}
	
	@Override
	public int play(Board b) {
		bp.setBoard(b);
		
		int col = -1;
		while(!b.isPlayable(col)) {
			col = getClic();
		}
		
		bp.play(col, getToken());
		return col;
	}
	
	private int getClic() {
		try {
			int col = play.poll(Long.MAX_VALUE, TimeUnit.DAYS);
			return col;
		} catch(InterruptedException e) {
			e.printStackTrace();
			return -1;
		}
	}
	
	@Override
	public void played(int col) {
		bp.play(col, getToken().next());
	}
	
	@Override
	public String toString() {
		return "UIPlayer Swing";
	}
	
	class ClicListener extends MouseAdapter {
		@Override
		public void mouseReleased(MouseEvent e) {
			int x = e.getX();
			int col = bp.getColumn(x);
			play.offer(col);
		}
	}
}
